package com.controller;

import com.model.FlightModel;
import com.services.IFlightManageServices;
import com.services.impl.FlightManageServicesImpl;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/manage/flights/*")
public class FlightManageController extends HttpServlet {
    private IFlightManageServices flightManageServices = new FlightManageServicesImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        String pathInfo = request.getPathInfo();
        Map<String, Object> result = new HashMap<>();

        try {
            if (pathInfo == null || pathInfo.equals("/")) {
                // 获取航班列表或创建新航班
                String action = request.getParameter("action");
                if ("list".equals(action)) {
                    handleGetFlightList(request, result);
                } else {
                    handleCreateFlight(request, result);
                }
            } else if (pathInfo.matches("/\\d+")) {
                // 更新航班信息
                handleUpdateFlight(request, result, pathInfo);
            } else if (pathInfo.matches("/\\d+/delete")) {
                // 删除航班
                handleDeleteFlight(request, result, pathInfo);
            } else if (pathInfo.matches("/\\d+/activate")) {
                // 上架航班
                handleActivateFlight(request, result, pathInfo);
            } else if (pathInfo.matches("/\\d+/deactivate")) {
                // 下架航班
                handleDeactivateFlight(request, result, pathInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", "操作失败：" + e.getMessage());
        }

        response.getWriter().write(JSONObject.fromObject(result).toString());
    }

    private void handleGetFlightList(HttpServletRequest request, Map<String, Object> result) throws Exception {
        int page = Integer.parseInt(request.getParameter("page"));
        int size = Integer.parseInt(request.getParameter("size"));
        String query = request.getParameter("query");

        Map<String, Object> flightsData = flightManageServices.getFlightList(page, size, query);
        result.put("code", 0);
        result.put("msg", "success");
        result.put("data", flightsData);
    }

    private void handleCreateFlight(HttpServletRequest request, Map<String, Object> result) throws Exception {
        // 读取请求体
        BufferedReader reader = request.getReader();
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }

        JSONObject flightData = JSONObject.fromObject(sb.toString());
        FlightModel flight = (FlightModel) JSONObject.toBean(flightData, FlightModel.class);
        
        FlightModel createdFlight = flightManageServices.createFlight(flight);
        result.put("code", 0);
        result.put("msg", "航班创建成功");
        result.put("data", createdFlight);
    }

    private void handleUpdateFlight(HttpServletRequest request, Map<String, Object> result, String pathInfo) throws Exception {
        int flightId = Integer.parseInt(pathInfo.substring(1));
        
        BufferedReader reader = request.getReader();
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }

        JSONObject flightData = JSONObject.fromObject(sb.toString());
        FlightModel flight = (FlightModel) JSONObject.toBean(flightData, FlightModel.class);
        flight.setFlightId(flightId);

        FlightModel updatedFlight = flightManageServices.updateFlight(flight);
        result.put("code", 0);
        result.put("msg", "航班更新成功");
        result.put("data", updatedFlight);
    }

    private void handleDeleteFlight(HttpServletRequest request, Map<String, Object> result, String pathInfo) throws Exception {
        int flightId = Integer.parseInt(pathInfo.substring(1, pathInfo.indexOf("/delete")));
        flightManageServices.deleteFlight(flightId);
        result.put("code", 0);
        result.put("msg", "航班删除成功");
    }

    private void handleActivateFlight(HttpServletRequest request, Map<String, Object> result, String pathInfo) throws Exception {
        int flightId = Integer.parseInt(pathInfo.substring(1, pathInfo.indexOf("/activate")));
        flightManageServices.updateFlightStatus(flightId, "ACTIVE");
        result.put("code", 0);
        result.put("msg", "航班已上架");
    }

    private void handleDeactivateFlight(HttpServletRequest request, Map<String, Object> result, String pathInfo) throws Exception {
        int flightId = Integer.parseInt(pathInfo.substring(1, pathInfo.indexOf("/deactivate")));
        flightManageServices.updateFlightStatus(flightId, "INACTIVE");
        result.put("code", 0);
        result.put("msg", "航班已下架");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doPost(request, response);
    }
} 